package com.lyw.utils;

import com.lyw.Window;
import com.lyw.exception.GlobalException;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;

public class GlobalConfigUtil {

    public static final Properties PROPERTIES = new Properties();

    static {
        try {
            FileInputStream inputStream = new FileInputStream(new File(Objects.requireNonNull(Window.class.getClassLoader().getResource("config/TPlan.properties")).getPath()));
            PROPERTIES.load(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Object setClassValueByFieldNames(List<String> fieldNames, Class<?> clazz) {

        return ReflectUtil.setClassValueByFieldNames(fieldNames, PROPERTIES, clazz);
    }

    public static void editSimplePropertiesFileValue(String key, String value) {
        /*String property = PROPERTIES.getProperty(key);
        if (property == null) {
            throw new GlobalException(StringUtil.format("当前 key = {} 对应的配置信息不存在！", key));
        }*/
        PROPERTIES.setProperty(key, value);
        try {
            PROPERTIES.store(new OutputStreamWriter(new FileOutputStream(new File(Objects.requireNonNull(Window.class.getClassLoader().getResource("config/TPlan.properties")).getPath())), StandardCharsets.UTF_8), "切换角色！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void batchEditPropertiesFileInfo(Map<String, String> info) {

        if (info == null || info.size() == 0) {
            throw new GlobalException("需要修改的配置信息不能为空！");
        }

        for (String key : info.keySet()) {
            String value = info.get(key);
            editSimplePropertiesFileValue(key, value);
        }
    }

}
